package com.imooc.bilibili.api;

import com.alibaba.fastjson.JSONObject;
import com.imooc.bilibili.api.support.UserSupport;
import com.imooc.bilibili.domain.*;
import com.imooc.bilibili.service.UserFollowingService;
import com.imooc.bilibili.service.UserService;
import com.imooc.bilibili.service.util.RSAUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserApi {

    @Autowired
    private UserService userService;

    @Autowired
    private UserSupport userSupport;

    @Autowired
    private UserFollowingService userFollowingService;


    @GetMapping("/rsa-pks")
    public JsonResponse<String> getRsaPublicKey() {
        String keyStr = RSAUtil.getPublicKeyStr();
        return new JsonResponse<>(keyStr);
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @PostMapping("/users")
    public JsonResponse<String> addUser(@RequestBody User user) {

        userService.addUser(user);
        return JsonResponse.success();
    }

    @GetMapping("/users")
    public JsonResponse<User> getUserInfo() {

        Long userId = userSupport.getCurrentUserId();
        User user = userService.getUserById(userId);

        return new JsonResponse<>(user);
    }

    @PutMapping("/users")
    public JsonResponse<String> updateUsers(@RequestBody User user) throws Exception {

        Long userId = userSupport.getCurrentUserId();
        user.setId(userId);
        userService.updateUser(user);
        return JsonResponse.success();
    }

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/user-tokens")
    public JsonResponse<String> login(@RequestBody User user) throws Exception {

        String token = userService.login(user);
        return new JsonResponse<>(token);
    }

    @PutMapping("/user-infos")
    public JsonResponse<String> updateUserInfos(@RequestBody UserInfo userInfo) {

        Long userId = userSupport.getCurrentUserId();
        userInfo.setUserId(userId);
        userService.updateUserInfo(userInfo);
        return JsonResponse.success();
    }

    @GetMapping("/user-infos")
    public JsonResponse<PageResult<UserInfo>> pageListUserInfos(@RequestParam Integer no, @RequestParam Integer size, String nick) {

        Long userId = userSupport.getCurrentUserId();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("no", no);
        jsonObject.put("size", size);
        jsonObject.put("nick", nick);
        jsonObject.put("userId", userId);

        PageResult<UserInfo> result = userService.pageListUserInfos(jsonObject);
        if (result.getTotal() > 0) {
            List<UserInfo> userInfoList = userFollowingService.checkFollowingStatus(result.getList(), userId);
            result.setList(userInfoList);
        }
        return new JsonResponse<>(result);
    }
}
